package com.zueb.service.impl;

import com.zueb.mapper.AdminMapper;
import com.zueb.pojo.Admin;
import com.zueb.service.AdminService;
import com.zueb.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class AdminServiceImpl implements AdminService {
    //1. 创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public Admin getAdminByName(String adminName){
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        //调用方法
        Admin admin = adminMapper.getByAdminName(adminName);
        //释放资源
        sqlSession.close();
        return admin;
    }

    @Override
    public List<Admin> getAllAdmin(int curPage, int pageSize) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        int index = pageSize * (curPage - 1);
        //调用方法
        List<Admin> admins = adminMapper.getAllAdmin(index, pageSize);
        //释放资源
        sqlSession.close();
        return admins;
    }

    @Override
    public int getAllCount() {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        //调用方法
        int totalCount = adminMapper.getAllCount();
        //释放资源
        sqlSession.close();
        return totalCount;
    }

    @Override
    public void addAdmin(Admin admin) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        //调用方法
        adminMapper.addAdmin(admin);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    @Override
    public void deleteAdmin(Integer adminId) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession(true);
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        //调用方法
        adminMapper.deleteByAdminId(adminId);
        //释放资源
        sqlSession.close();
    }

    @Override
    public void updateAdmin(Admin admin) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession(true);
        //获取Mapper
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        //调用方法
        adminMapper.updateAdmin(admin);
        //释放资源
        sqlSession.close();
    }


}
